package com.sgcc.nfc.lock.data.repository

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.core.network.safeApiCall
import com.sgcc.nfc.lock.core.network.safeApiCallVoid
import com.sgcc.nfc.lock.data.remote.api.CreateUserRequest
import com.sgcc.nfc.lock.data.remote.api.UpdateUserRequest
import com.sgcc.nfc.lock.data.remote.api.UserApi
import com.sgcc.nfc.lock.domain.model.PagedList
import com.sgcc.nfc.lock.domain.model.UserProfile
import com.sgcc.nfc.lock.domain.repository.UserRepository
import javax.inject.Inject

class UserRepositoryImpl @Inject constructor(
    private val userApi: UserApi
) : UserRepository {

    override suspend fun getUsers(
        page: Int,
        pageSize: Int,
        roleType: Int?,
        regionId: Long?,
        keyword: String?
    ): NetworkResult<PagedList<UserProfile>> {
        val response = safeApiCall {
            userApi.getUsers(page, pageSize, roleType, regionId, keyword)
        }
        return when (response) {
            is NetworkResult.Success -> NetworkResult.Success(response.data.map { it.toDomain() })
            is NetworkResult.Error -> response
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }

    override suspend fun createUser(request: UserRepository.CreateUserParams): NetworkResult<Unit> {
        val body = CreateUserRequest(
            username = request.username,
            password = request.password,
            realName = request.realName,
            phone = request.phone,
            roleType = request.roleType,
            regionId = request.regionId
        )
        return safeApiCallVoid { userApi.createUser(body) }
    }

    override suspend fun updateUser(request: UserRepository.UpdateUserParams): NetworkResult<Unit> {
        val body = UpdateUserRequest(
            realName = request.realName,
            phone = request.phone,
            roleType = request.roleType,
            regionId = request.regionId
        )
        return safeApiCallVoid { userApi.updateUser(request.userId, body) }
    }

    override suspend fun deleteUser(userId: Long): NetworkResult<Unit> =
        safeApiCallVoid { userApi.deleteUser(userId) }

    override suspend fun resetPassword(userId: Long): NetworkResult<Unit> =
        safeApiCallVoid { userApi.resetPassword(userId) }
}
